package server;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.CharsetUtil;
public class MyTestDecoder1  extends SimpleChannelInboundHandler<Object> {

    private WebSocketServerHandshaker handshaker;

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest){
            System.out.println("-------web socket 建立连接-----");
            handleHttpRequest(ctx,(FullHttpRequest)msg);
        }else if (msg instanceof WebSocketFrame){
            ByteBuf content = ((BinaryWebSocketFrame) msg).content();
            if(content.readableBytes()==1 && content.readByte()==16){
                System.out.println("-------开始回复------");
                ByteBuf buffer = ctx.alloc().buffer();
                buffer.writeByte(32);
                ctx.channel().writeAndFlush(buffer);
            }else{
                ctx.fireChannelRead(((BinaryWebSocketFrame) msg).content());
            }

        }else {
            System.out.println("-----------错误----------");
        }

    }

    /**
     * 唯一的一次http请求，用于创建websocket
     * */
    private void handleHttpRequest(ChannelHandlerContext ctx,
                                   FullHttpRequest req) {

        //要求Upgrade为websocket，过滤掉get/Post
        if (!req.decoderResult().isSuccess()
                || (!"websocket".equals(req.headers().get("Upgrade")))) {
            //若不是websocket方式，则创建BAD_REQUEST的req，返回给客户端
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                "ws://localhost:1883/go/1/a", null, false);

        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            DefaultHttpHeaders entries = new DefaultHttpHeaders();
            entries.add("Sec-WebSocket-Protocol","mqtt");
            handshaker.handshake(ctx.channel(), req,entries,ctx.channel().newPromise());
        }
    }
    /**
     * 拒绝不合法的请求，并返回错误信息
     * */
    private static void sendHttpResponse(ChannelHandlerContext ctx,
                                         FullHttpRequest req, DefaultFullHttpResponse res) {

        // 返回应答给客户端
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(),
                    CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        // 如果是非Keep-Alive，关闭连接
//        if (!isKeepAlive(req) || res.status().code() != 200) {
//            f.addListener(ChannelFutureListener.CLOSE);
//        }
    }

    /**
     * 字节数组转二进制
     * @param nByte
     * @return
     */
    public String Byte2String(byte[] nByte){
        StringBuilder s=new StringBuilder();
        for (byte b : nByte) {
            StringBuilder nStr=new StringBuilder();
            for(int i=7;i>=0;i--){
                int j=(int)b & (int)(Math.pow(2, (double)i));
                if(j>0){
                    nStr.append("1");
                }else {
                    nStr.append("0");
                }
            }
            s.append(nStr);
            s.append(" ");
        }
      return s.toString();
//        StringBuilder nStr=new StringBuilder();
//        for(int i=7;i>=0;i--){
//            int j=(int)nByte & (int)(Math.pow(2, (double)i));
//            if(j>0){
//                nStr.append("1");
//            }else {
//                nStr.append("0");
//            }
//        }
//        return nStr.toString();

    }


    /**
     * 字节数组转16进制
     * @param bArray
     * @return
     */
    public String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }


}

